package controller

import (
	. "api/model"
	"net/http"
	"strconv"
	"github.com/gin-gonic/gin"
)

func GetCreditCard(c *gin.Context) {
	s := CreditCard{}

	ret, err := s.GetCreditCard()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}
	if ret == nil {
		ret = make([]*CreditCard, 0)
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success", "data": ret})
}

func GetCreditCardDetails(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	s := CreditCard{}
	ret, err := s.GetCreditCardDetails(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success", "data": ret})
}

func CreateCreditCard(c *gin.Context) {
	s := CreditCard{}

	err := c.BindJSON(&s)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	}

	if (s.PromotionOfficerAward + s.ApprenticeAward >= s.TotalPromotionFee) {
		c.JSON(http.StatusOK, gin.H{"error": "推广官奖励 + 徒弟出单奖励 < 总推广费用"})
		return
	}

	err = s.CreateCreditCard(&s)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}

func UpdateCreditCard(c *gin.Context) {
	s := CreditCard{}

	err := c.BindJSON(&s)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	}

	if (s.PromotionOfficerAward + s.ApprenticeAward >= s.TotalPromotionFee) {
		c.JSON(http.StatusOK, gin.H{"error": "推广官奖励 + 徒弟出单奖励 < 总推广费用"})
		return
	}

	err = s.UpdateCreditCard(&s)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}

func DeleteCreditCard(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	status, err := strconv.Atoi(c.Query("status"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	s := CreditCard{}

	err = s.DeleteCreditCard(status, id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}